package com.woniu.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.woniu.dto.BloodDto;
import com.woniu.exception.CheckException;
import com.woniu.dto.QueryBloodDto;
import com.woniu.model.HisBlood;
import com.woniu.mapper.HisBloodMapper;
import com.woniu.param.CreateBloodParam;
import com.woniu.param.QueryBloodParam;
import com.woniu.service.IHisBloodService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniu.util.CopyBeanUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 血检表 服务实现类
 * </p>
 *
 * @author ${author}
 * @since 2021-11-11
 */
@Service
public class HisBloodServiceImpl extends ServiceImpl<HisBloodMapper, HisBlood> implements IHisBloodService {

    //查询血检结果
    @Override
    public QueryBloodDto queryBlood(QueryBloodParam queryBloodParam) {
        //时间倒序查找
        QueryWrapper<HisBlood> wrapper = new QueryWrapper<HisBlood>().orderByDesc("raw_add_time");

        //查询条件
        if (ObjectUtil.isNotNull(queryBloodParam.getBloodId())) {
            wrapper.eq("blood_id", queryBloodParam.getBloodId());
        }
        if (ObjectUtil.isNotNull(queryBloodParam.getBloodName())) {
            wrapper.eq("blood_name", queryBloodParam.getBloodName());
        }
        if (ObjectUtil.isNotNull(queryBloodParam.getCaseId())) {
            wrapper.eq("case_id", queryBloodParam.getCaseId());
        }
        if (ObjectUtil.isNotNull(queryBloodParam.getCheckId())) {
            wrapper.eq("check_id", queryBloodParam.getCheckId());
        }

        List<HisBlood> bloodList = this.list(wrapper);

        if(ObjectUtil.isNull(bloodList)) {
            throw new CheckException(1001, "无血检结果");
        }

        QueryBloodDto dto = new QueryBloodDto();
        List<BloodDto> bloodDtoList = CopyBeanUtil.copyBean(bloodList, BloodDto.class);
        dto.setBloodDtoList(bloodDtoList);

        return dto;
    }

    //添加血检
    @Override
    public QueryBloodDto createBlood(CreateBloodParam createBloodParam) {

        HisBlood blood = new HisBlood();
        BeanUtils.copyProperties(createBloodParam, blood);

        if (!this.save(blood)) {
            throw new CheckException(1001, "血检结果保存失败");
        }

        QueryBloodDto dto = new QueryBloodDto();
        BeanUtils.copyProperties(blood, dto);
        return dto;
    }
}
